#pragma once

#include<iostream>
#include<string>

using namespace std;

const std::string blank_space_sep=" ";
const std::string protocol_sep="\n";

//封装报头
string Encode(string& content)
{
    string package=to_string(content.size());
    package+=protocol_sep;
    package+=content;
    package+=protocol_sep;

    return package;
}

//去封装，将有效载荷赋给content
bool Decode(string& package,string& content)
{
    size_t pos=package.find(protocol_sep);
    if(pos==string::npos)return false;

    string len_str=package.substr(0,pos);
    size_t len=stoi(len_str);

    size_t total_len=len_str.size()+len+2;//有问题！！
    if(package.size()<total_len)return false;

    content=package.substr(pos+1,len);

    //移除报文 package.erase()
    package.erase(0,total_len);
    return true;
}

class Request
{
public:
    Request(int data1=0,int data2=0,char opr=' '):_x(data1),_y(data2),_opr(opr)
    {}
public:
    //序列化————在数据发收的过程中，判断数据完整性
    bool Serialize(string& out)
    {
        //构建报文的有效载荷  序列化——>"x opr y"
        out=to_string(_x);
        out+=blank_space_sep;
        out+=_opr;
        out+=blank_space_sep;
        out+=to_string(_y);

        return true;
    }
    //反序列化————在数据发收的过程中，判断数据完整性
    bool Deserialize(const string& in)
    {
        size_t left=in.find(blank_space_sep);
        if(left==string::npos)return false;
        string x=in.substr(0,left);

        size_t right=in.rfind(blank_space_sep);
        if(right==string::npos)return false;
        string y=in.substr(right+1);

        if(left+2!=right)return false;

        _opr=in[left+1];
        _x=stoi(x);
        _y=stoi(y);

        return true;
    }
    void DebugPrint()
    {
        cout<<"新任务构建完成： "<<_x<<_opr<<_y<<"=?"<<endl;
    }
public:
    int _x;
    int _y;
    char _opr;//+ - * / %
};

class Response
{
public:
    Response(int res=0,int code=-1):_result(res),_code(code)
    {}
public:
    bool Serialize(string& out)
    {
        //构建报文的有效载荷  "len\n"result [code]"
        out=to_string(_result);
        out+=blank_space_sep;
        //out+="[";
        out+=to_string(_code);
        //out+="]";

        return true;
    }
    bool Deserialize(const string& in)
    {
        size_t pos=in.find(blank_space_sep);
        if(pos==string::npos)return false;
        string result=in.substr(0,pos);
        string code=in.substr(pos+1);

        _result=stoi(result);
        _code=stoi(code);

        return true;
    }
    void DebugPrint()
    {
        cout<<"响应完成,result:"<<_result<<",code:"<<_code<<"\n"<<endl;
    }
public:
    int _result;
    int _code;//0，可信；非0，错误
};